<template>
  <div class="birth-report">
    <el-card>
      <template #header>
        <span>出生申报</span>
      </template>
      
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" v-loading="loading">
        <!-- 新生儿信息 -->
        <el-divider content-position="left">新生儿信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="新生儿姓名" prop="childName">
              <el-input v-model="form.childName" placeholder="请输入新生儿姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="childGender">
              <el-select v-model="form.childGender" placeholder="请选择性别" style="width: 100%">
                <el-option label="男" :value="1" />
                <el-option label="女" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="出生日期" prop="birthDate">
              <el-date-picker
                v-model="form.birthDate"
                type="date"
                placeholder="请选择出生日期"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出生地点" prop="birthPlace">
              <el-input v-model="form.birthPlace" placeholder="请输入出生地点" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="出生证明编号" prop="birthCertificateNo">
          <el-input v-model="form.birthCertificateNo" placeholder="请输入出生证明编号" style="width: 50%" />
        </el-form-item>
        
        <!-- 父母信息 -->
        <el-divider content-position="left">父母信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="父亲身份证号" prop="fatherIdCard">
              <el-input
                v-model="form.fatherIdCard"
                placeholder="请输入父亲身份证号"
                maxlength="18"
                show-word-limit
                :loading="fatherLoading"
                @input="handleFatherIdCardInput"
                @blur="handleFatherIdCardBlur"
              >
                <template #suffix>
                  <el-icon v-if="fatherLoading" class="is-loading"><Loading /></el-icon>
                  <el-icon v-else-if="fatherInfo.name" color="#67c23a"><CircleCheck /></el-icon>
                  <el-icon v-else-if="form.fatherIdCard && form.fatherIdCard.length === 18 && !validateIdCard(form.fatherIdCard)" color="#f56c6c"><CircleClose /></el-icon>
                </template>
              </el-input>
              <div v-if="fatherInfo.name" class="person-info-display">
                <el-tag type="primary" size="small">
                  <el-icon><Male /></el-icon>
                  {{ fatherInfo.name }} - {{ fatherInfo.phone || '无电话' }}
                </el-tag>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="母亲身份证号" prop="motherIdCard">
              <el-input
                v-model="form.motherIdCard"
                placeholder="请输入母亲身份证号"
                maxlength="18"
                show-word-limit
                :loading="motherLoading"
                @input="handleMotherIdCardInput"
                @blur="handleMotherIdCardBlur"
              >
                <template #suffix>
                  <el-icon v-if="motherLoading" class="is-loading"><Loading /></el-icon>
                  <el-icon v-else-if="motherInfo.name" color="#67c23a"><CircleCheck /></el-icon>
                  <el-icon v-else-if="form.motherIdCard && form.motherIdCard.length === 18 && !validateIdCard(form.motherIdCard)" color="#f56c6c"><CircleClose /></el-icon>
                </template>
              </el-input>
              <div v-if="motherInfo.name" class="person-info-display">
                <el-tag type="danger" size="small">
                  <el-icon><Female /></el-icon>
                  {{ motherInfo.name }} - {{ motherInfo.phone || '无电话' }}
                </el-tag>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 户籍选择 -->
        <el-divider content-position="left">户籍选择</el-divider>
        <div v-if="householdOptions.length > 0" class="household-selection">
          <!-- 父母同户籍情况 -->
          <div v-if="isSameHousehold" class="same-household-info">
            <el-alert
              title="父母在同一户籍"
              type="info"
              :closable="false"
              show-icon
              class="mb-4"
            >
              <template #default>
                <p>检测到父母在同一户籍，新生儿将自动加入该户籍。</p>
              </template>
            </el-alert>
            
            <el-form-item label="户籍信息" prop="targetHouseholdId">
              <div class="household-card same-household">
                <el-card shadow="hover" class="household-option-card">
                  <div class="household-info">
                    <div class="household-header">
                      <el-tag type="success" size="large">
                        <el-icon><House /></el-icon>
                        共同户籍
                      </el-tag>
                    </div>
                    <div class="household-details">
                      <p><strong>户号：</strong>{{ householdOptions[0].householdNumber }}</p>
                      <p><strong>户主：</strong>{{ householdOptions[0].name }}</p>
                      <p><strong>地址：</strong>{{ householdOptions[0].address }}</p>
                    </div>
                  </div>
                </el-card>
              </div>
            </el-form-item>
          </div>
          
          <!-- 父母不同户籍情况 -->
          <div v-else class="different-household-selection">
            <el-alert
              title="请选择新生儿跟随的户籍"
              type="warning"
              :closable="false"
              show-icon
              class="mb-4"
            >
              <template #default>
                <p>父母分别在不同户籍，请选择新生儿要加入的户籍。</p>
              </template>
            </el-alert>
            
            <el-form-item label="选择户籍" prop="targetHouseholdId">
              <el-radio-group v-model="form.targetHouseholdId" class="household-radio-group">
                <div class="household-options">
                  <el-radio
                    v-for="household in householdOptions"
                    :key="household.id"
                    :value="household.id"
                    class="household-radio"
                  >
                    <el-card shadow="hover" class="household-option-card">
                      <div class="household-info">
                        <div class="household-header">
                          <el-tag :type="household.parentType === 'father' ? 'primary' : 'danger'" size="large">
                            <el-icon v-if="household.parentType === 'father'"><Male /></el-icon>
                            <el-icon v-else><Female /></el-icon>
                            {{ household.parentType === 'father' ? '父亲户籍' : '母亲户籍' }}
                          </el-tag>
                        </div>
                        <div class="household-details">
                          <p><strong>户号：</strong>{{ household.householdNumber }}</p>
                          <p><strong>户主：</strong>{{ household.name }}</p>
                          <p><strong>地址：</strong>{{ household.address }}</p>
                        </div>
                      </div>
                    </el-card>
                  </el-radio>
                </div>
              </el-radio-group>
            </el-form-item>
          </div>
        </div>
        
        <div v-else-if="form.fatherId || form.motherId" class="no-household-info">
          <el-alert
            title="暂无可选户籍"
            type="warning"
            :closable="false"
            show-icon
          >
            <template #default>
              <p>请确认父母信息是否正确，或联系管理员处理户籍信息。</p>
            </template>
          </el-alert>
        </div>
        
        <!-- 备注信息 -->
        <el-divider content-position="left">其他信息</el-divider>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息（可选）"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="loading">
            提交申报
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { House, Male, Female, Loading, CircleCheck, CircleClose } from '@element-plus/icons-vue'
import axios from 'axios'
import { API_BASE_URL } from '@/config/api'

const formRef = ref()
const loading = ref(false)
const fatherLoading = ref(false)
const motherLoading = ref(false)

// 常量配置
const DEBOUNCE_DELAY = 800 // 防抖延迟时间（毫秒）

// 表单数据
const form = reactive({
  childName: '',
  childGender: null,
  birthDate: '',
  birthPlace: '',
  birthCertificateNo: '',
  fatherIdCard: '',
  motherIdCard: '',
  fatherId: null,
  motherId: null,
  targetHouseholdId: null,
  remark: ''
})

// 父母信息
const fatherInfo = ref({})
const motherInfo = ref({})

// 防抖定时器
const fatherDebounceTimer = ref(null)
const motherDebounceTimer = ref(null)

// 户籍选项
const householdOptions = ref([])
const fatherHousehold = ref(null)
const motherHousehold = ref(null)

// 计算属性：判断父母是否在同一户籍
const isSameHousehold = computed(() => {
  if (!fatherHousehold.value || !motherHousehold.value) return false
  return fatherHousehold.value.id === motherHousehold.value.id
})

// 监听父母同户籍状态变化
watch(isSameHousehold, (newVal) => {
  if (newVal && householdOptions.value.length > 0) {
    // 父母同户籍时自动选择该户籍
    form.targetHouseholdId = householdOptions.value[0].id
  } else {
    // 父母不同户籍时清空选择
    form.targetHouseholdId = null
  }
})

// 表单验证规则
const rules = {
  childName: [
    { required: true, message: '请输入新生儿姓名', trigger: 'blur' }
  ],
  childGender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  birthDate: [
    { required: true, message: '请选择出生日期', trigger: 'change' }
  ],
  birthPlace: [
    { required: true, message: '请输入出生地点', trigger: 'blur' }
  ],
  birthCertificateNo: [
    { required: true, message: '请输入出生证明编号', trigger: 'blur' }
  ],
  fatherIdCard: [
    { required: true, message: '请输入父亲身份证号', trigger: 'blur' },
    { 
      pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, 
      message: '请输入正确的身份证号码', 
      trigger: 'blur' 
    }
  ],
  motherIdCard: [
    { required: true, message: '请输入母亲身份证号', trigger: 'blur' },
    { 
      pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, 
      message: '请输入正确的身份证号码', 
      trigger: 'blur' 
    }
  ],
  targetHouseholdId: [
    { required: true, message: '请选择户籍', trigger: 'change' }
  ]
}

// 身份证号验证函数
const validateIdCard = (idCard) => {
  const pattern = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
  return pattern.test(idCard)
}

// 根据身份证号获取人员信息
const getPersonByIdCard = async (idCard) => {
  try {
    const token = localStorage.getItem('token')
    const response = await axios.get(`${API_BASE_URL}/person/getByIdCard`, {
      params: { idCard },
      headers: { token }
    })
    
    if (response.data.status === 200) {
      return response.data.data
    }
    return null
  } catch (error) {
    console.error('根据身份证号获取人员信息失败:', error)
    return null
  }
}

// 处理父亲身份证号输入（防抖）
const handleFatherIdCardInput = (value) => {
  // 清除之前的定时器
  if (fatherDebounceTimer.value) {
    clearTimeout(fatherDebounceTimer.value)
  }
  
  // 清空之前的信息
  fatherInfo.value = {}
  form.fatherId = null
  fatherHousehold.value = null
  
  // 如果输入为空或长度不够，直接返回
  if (!value || value.length < 18) {
    updateHouseholdOptions()
    return
  }
  
  // 验证身份证号格式
  if (!validateIdCard(value)) {
    // 如果格式不正确且长度为18位，显示错误提示
    if (value.length === 18) {
      ElMessage.error('父亲身份证号格式不正确，请检查后重新输入')
    }
    updateHouseholdOptions()
    return
  }
  
  // 设置防抖定时器（800ms）
  fatherDebounceTimer.value = setTimeout(async () => {
    await fetchFatherInfo(value)
  }, DEBOUNCE_DELAY)
}

// 处理母亲身份证号输入（防抖）
const handleMotherIdCardInput = (value) => {
  // 清除之前的定时器
  if (motherDebounceTimer.value) {
    clearTimeout(motherDebounceTimer.value)
  }
  
  // 清空之前的信息
  motherInfo.value = {}
  form.motherId = null
  motherHousehold.value = null
  
  // 如果输入为空或长度不够，直接返回
  if (!value || value.length < 18) {
    updateHouseholdOptions()
    return
  }
  
  // 验证身份证号格式
  if (!validateIdCard(value)) {
    // 如果格式不正确且长度为18位，显示错误提示
    if (value.length === 18) {
      ElMessage.error('母亲身份证号格式不正确，请检查后重新输入')
    }
    updateHouseholdOptions()
    return
  }
  
  // 设置防抖定时器（800ms）
  motherDebounceTimer.value = setTimeout(async () => {
    await fetchMotherInfo(value)
  }, DEBOUNCE_DELAY)
}

// 处理父亲身份证号失焦
const handleFatherIdCardBlur = () => {
  const value = form.fatherIdCard
  if (value && value.length === 18 && validateIdCard(value) && !fatherInfo.value.name) {
    // 如果身份证号完整且格式正确，但还没有获取到信息，立即获取
    fetchFatherInfo(value)
  }
}

// 处理母亲身份证号失焦
const handleMotherIdCardBlur = () => {
  const value = form.motherIdCard
  if (value && value.length === 18 && validateIdCard(value) && !motherInfo.value.name) {
    // 如果身份证号完整且格式正确，但还没有获取到信息，立即获取
    fetchMotherInfo(value)
  }
}

// 获取父亲信息
const fetchFatherInfo = async (idCard) => {
  // 防止重复请求
  if (fatherLoading.value) return
  
  fatherLoading.value = true
  try {
    const person = await getPersonByIdCard(idCard)
    
    // 检查身份证号是否还匹配（防止异步竞态条件）
    if (form.fatherIdCard !== idCard) {
      return
    }
    
    if (person) {
      // 验证性别（父亲应该是男性）
      if (person.gender !== 1) {
        ElMessage.error('该身份证号对应的人员性别不是男性，请确认父亲身份证号是否正确')
        return
      }
      
      // 设置父亲信息
      fatherInfo.value = person
      form.fatherId = person.id
      
      // 获取父亲户籍信息
      const household = await getPersonHousehold(person.id)
      
      // 再次检查身份证号是否还匹配
      if (form.fatherIdCard !== idCard) {
        return
      }
      
      if (household) {
        fatherHousehold.value = household
        ElMessage.success(`已找到父亲信息：${person.name}`)
      } else {
        ElMessage.warning(`已找到父亲信息：${person.name}，但未找到对应户籍信息`)
      }
      
      // 更新户籍选项
      updateHouseholdOptions()
    } else {
      ElMessage.error('未找到该身份证号对应的人员信息，请确认身份证号是否正确')
    }
  } catch (error) {
    // 检查身份证号是否还匹配
    if (form.fatherIdCard !== idCard) {
      return
    }
    
    console.error('获取父亲信息失败:', error)
    if (error.response?.status === 404) {
      ElMessage.error('未找到该身份证号对应的人员信息')
    } else if (error.response?.status === 400) {
      ElMessage.error('身份证号格式不正确')
    } else {
      ElMessage.error('获取父亲信息失败，请稍后重试')
    }
  } finally {
    fatherLoading.value = false
  }
}

// 获取母亲信息
const fetchMotherInfo = async (idCard) => {
  // 防止重复请求
  if (motherLoading.value) return
  
  motherLoading.value = true
  try {
    const person = await getPersonByIdCard(idCard)
    
    // 检查身份证号是否还匹配（防止异步竞态条件）
    if (form.motherIdCard !== idCard) {
      return
    }
    
    if (person) {
      // 验证性别（母亲应该是女性）
      if (person.gender !== 2) {
        ElMessage.error('该身份证号对应的人员性别不是女性，请确认母亲身份证号是否正确')
        return
      }
      
      // 设置母亲信息
      motherInfo.value = person
      form.motherId = person.id
      
      // 获取母亲户籍信息
      const household = await getPersonHousehold(person.id)
      
      // 再次检查身份证号是否还匹配
      if (form.motherIdCard !== idCard) {
        return
      }
      
      if (household) {
        motherHousehold.value = household
        ElMessage.success(`已找到母亲信息：${person.name}`)
      } else {
        ElMessage.warning(`已找到母亲信息：${person.name}，但未找到对应户籍信息`)
      }
      
      // 更新户籍选项
      updateHouseholdOptions()
    } else {
      ElMessage.error('未找到该身份证号对应的人员信息，请确认身份证号是否正确')
    }
  } catch (error) {
    // 检查身份证号是否还匹配
    if (form.motherIdCard !== idCard) {
      return
    }
    
    console.error('获取母亲信息失败:', error)
    if (error.response?.status === 404) {
      ElMessage.error('未找到该身份证号对应的人员信息')
    } else if (error.response?.status === 400) {
      ElMessage.error('身份证号格式不正确')
    } else {
      ElMessage.error('获取母亲信息失败，请稍后重试')
    }
  } finally {
    motherLoading.value = false
  }
}

// 获取人员户籍信息
const getPersonHousehold = async (personId) => {
  try {
    console.log('DEBUG: 开始获取人员户籍信息, personId =', personId)
    const token = localStorage.getItem('token')
    const response = await axios.get(`${API_BASE_URL}/household/getPersonHousehold/${personId}`, {
      headers: { token }
    })
    
    console.log('DEBUG: getPersonHousehold 完整响应:', response.data)
    console.log('DEBUG: 响应状态:', response.data.status)
    console.log('DEBUG: 响应数据:', response.data.data)
    
    if (response.data.status === 200) {
      const householdData = response.data.data
      console.log('DEBUG: 解析后的户籍数据:', householdData)
      if (householdData) {
        console.log('DEBUG: 户籍ID:', householdData.id, '类型:', typeof householdData.id)
        console.log('DEBUG: 户号:', householdData.householdNumber)
        console.log('DEBUG: 户主姓名:', householdData.name)
        console.log('DEBUG: 地址:', householdData.address)
      }
      return householdData
    } else {
      console.log('DEBUG: 响应状态不是200:', response.data.status, response.data.msg)
    }
    return null
  } catch (error) {
    console.error('获取人员户籍信息失败:', error)
    return null
  }
}

// 处理父亲选择变化（保留兼容性）
const handleFatherChange = async (fatherId) => {
  if (!fatherId) {
    fatherHousehold.value = null
    updateHouseholdOptions()
    return
  }
  
  loading.value = true
  try {
    const household = await getPersonHousehold(fatherId)
    fatherHousehold.value = household
    updateHouseholdOptions()
  } catch (error) {
    ElMessage.error('获取父亲户籍信息失败')
  } finally {
    loading.value = false
  }
}

// 处理母亲选择变化（保留兼容性）
const handleMotherChange = async (motherId) => {
  if (!motherId) {
    motherHousehold.value = null
    updateHouseholdOptions()
    return
  }
  
  loading.value = true
  try {
    const household = await getPersonHousehold(motherId)
    motherHousehold.value = household
    updateHouseholdOptions()
  } catch (error) {
    ElMessage.error('获取母亲户籍信息失败')
  } finally {
    loading.value = false
  }
}

// 更新户籍选项
const updateHouseholdOptions = () => {
  console.log('DEBUG: 开始更新户籍选项')
  console.log('DEBUG: 父亲户籍信息:', fatherHousehold.value)
  console.log('DEBUG: 母亲户籍信息:', motherHousehold.value)
  
  const options = []
  
  // 添加父亲户籍
  if (fatherHousehold.value) {
    console.log('DEBUG: 添加父亲户籍到选项')
    options.push({
      ...fatherHousehold.value,
      parentType: 'father'
    })
  }
  
  // 添加母亲户籍（如果与父亲不同）
  if (motherHousehold.value) {
    const isDifferent = !fatherHousehold.value || 
                       fatherHousehold.value.id !== motherHousehold.value.id
    console.log('DEBUG: 母亲户籍是否与父亲不同:', isDifferent)
    if (isDifferent) {
      console.log('DEBUG: 添加母亲户籍到选项')
      options.push({
        ...motherHousehold.value,
        parentType: 'mother'
      })
    }
  }
  
  console.log('DEBUG: 最终户籍选项:', options)
  householdOptions.value = options
  
  // 自动设置targetHouseholdId
  if (isSameHousehold.value && options.length > 0) {
    form.targetHouseholdId = options[0].id
    console.log('DEBUG: 父母同户籍，自动设置targetHouseholdId =', form.targetHouseholdId)
  } else if (!isSameHousehold.value) {
    form.targetHouseholdId = null
    console.log('DEBUG: 父母不同户籍，清空targetHouseholdId')
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    
    loading.value = true
    
    try {
      const token = localStorage.getItem('token')
      if (!token) {
        ElMessage.error('请先登录')
        return
      }

      // 构建提交数据
      const submitData = {
        childName: form.childName,
        childGender: form.childGender,
        birthDate: form.birthDate ? new Date(form.birthDate).toISOString() : null,
        birthPlace: form.birthPlace,
        birthCertificateNo: form.birthCertificateNo,
        fatherId: form.fatherId ? String(form.fatherId) : null,
        motherId: form.motherId ? String(form.motherId) : null,
        targetHouseholdId: form.targetHouseholdId ? String(form.targetHouseholdId) : null,
        remark: form.remark || null
      }

      console.log('DEBUG: 提交数据详情:')
      console.log('DEBUG: submitData =', submitData)
      console.log('DEBUG: targetHouseholdId =', submitData.targetHouseholdId)
      console.log('DEBUG: targetHouseholdId类型 =', typeof submitData.targetHouseholdId)
      console.log('DEBUG: targetHouseholdId是否为null =', submitData.targetHouseholdId === null)
      console.log('DEBUG: targetHouseholdId是否为undefined =', submitData.targetHouseholdId === undefined)
      console.log('DEBUG: householdOptions =', householdOptions.value)
      console.log('DEBUG: fatherHousehold =', fatherHousehold.value)
      console.log('DEBUG: motherHousehold =', motherHousehold.value)
      
      const response = await axios.post(`${API_BASE_URL}/household/birthRegister`, submitData, {
        headers: {
          'token': token,
          'Content-Type': 'application/json'
        }
      })
      
      console.log('出生申报响应:', response.data)
      
      const result = response.data
      if (result.status === 200) {
        ElMessage.success(result.msg || '出生申报提交成功')
        handleReset()
      } else {
        ElMessage.error(result.msg || '出生申报提交失败')
      }
      
    } catch (error) {
      console.error('出生申报请求出错:', error)
      
      if (error.response) {
        const errorMsg = error.response.data?.msg || '服务器错误，请稍后重试'
        ElMessage.error(errorMsg)
      } else if (error.request) {
        ElMessage.error('网络连接失败，请检查网络')
      } else {
        ElMessage.error('出生申报失败: ' + error.message)
      }
    } finally {
      loading.value = false
    }
  })
}

// 重置表单
const handleReset = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  
  // 清空所有数据
  Object.assign(form, {
    childName: '',
    childGender: null,
    birthDate: '',
    birthPlace: '',
    birthCertificateNo: '',
    fatherIdCard: '',
    motherIdCard: '',
    fatherId: null,
    motherId: null,
    targetHouseholdId: null,
    remark: ''
  })
  
  // 清空父母信息
  fatherInfo.value = {}
  motherInfo.value = {}
  
  // 清空户籍信息
  householdOptions.value = []
  fatherHousehold.value = null
  motherHousehold.value = null
  
  // 重置加载状态
  fatherLoading.value = false
  motherLoading.value = false
  
  // 清除防抖定时器
  if (fatherDebounceTimer.value) {
    clearTimeout(fatherDebounceTimer.value)
    fatherDebounceTimer.value = null
  }
  if (motherDebounceTimer.value) {
    clearTimeout(motherDebounceTimer.value)
    motherDebounceTimer.value = null
  }
}

// 组件卸载时清理定时器
onUnmounted(() => {
  if (fatherDebounceTimer.value) {
    clearTimeout(fatherDebounceTimer.value)
  }
  if (motherDebounceTimer.value) {
    clearTimeout(motherDebounceTimer.value)
  }
})
</script>

<style lang="scss" scoped>
.birth-report {
  .el-form {
    max-width: 900px;
  }

  .el-divider {
    margin: 20px 0;
  }

  .el-divider__text {
    font-weight: 600;
    color: #409eff;
  }

  // 户籍选择区域样式
  .household-selection {
    .mb-4 {
      margin-bottom: 16px;
    }

    // 户籍选择整体容器
    .household-selection {
      margin: 20px 0;
      
      // 确保所有子元素不浮动
      * {
        float: none !important;
      }
    }

    // 同户籍显示样式
    .same-household-info {
      .household-card {
        margin: 16px 0;
        
        .household-option-card {
          border: 2px solid #67c23a;
          background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
          
          .household-info {
            padding: 20px;
            
            .household-header {
              margin-bottom: 16px;
              
              .el-tag {
                font-size: 14px;
                padding: 8px 16px;
                
                .el-icon {
                  margin-right: 6px;
                }
              }
            }
            
            .household-details {
              p {
                margin: 10px 0;
                font-size: 14px;
                color: #606266;
                line-height: 1.5;
                
                strong {
                  color: #303133;
                  margin-right: 8px;
                }
              }
            }
          }
        }
      }
    }

    // 不同户籍选择样式
    .different-household-selection {
      .household-radio-group {
        width: 100%;
        
        .household-options {
          display: block;
          width: 100%;
        }
        
        .household-radio {
          width: 100%;
          height: auto;
          margin: 0 0 24px 0 !important;
          display: block !important;
          position: relative;
          clear: both;
          
          // 重置Element Plus默认样式
          :deep(.el-radio__input) {
            position: absolute;
            top: 20px;
            right: 20px;
            z-index: 10;
            margin: 0;
          }
          
          :deep(.el-radio__label) {
            width: 100%;
            padding: 0 !important;
            display: block !important;
            margin: 0;
            line-height: normal;
          }
          
          // 确保每个radio独占一行
          &::after {
            content: "";
            display: block;
            clear: both;
            height: 0;
          }
          
          .household-option-card {
            width: 100%;
            cursor: pointer;
            transition: all 0.3s ease;
            border: 2px solid #e4e7ed;
            margin: 0 0 16px 0;
            display: block;
            position: relative;
            
            &:hover {
              border-color: #409eff;
              box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
              transform: translateY(-2px);
            }
            
            .household-info {
              padding: 20px;
              display: block;
              
              .household-header {
                margin-bottom: 16px;
                
                .el-tag {
                  font-size: 14px;
                  padding: 8px 16px;
                  
                  .el-icon {
                    margin-right: 6px;
                  }
                }
              }
              
              .household-details {
                p {
                  margin: 10px 0;
                  font-size: 14px;
                  color: #606266;
                  line-height: 1.5;
                  
                  strong {
                    color: #303133;
                    margin-right: 8px;
                  }
                }
              }
            }
          }
          
          // 选中状态样式
          &.is-checked {
            .household-option-card {
              border-color: #409eff;
              background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
              box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
            }
          }
        }
      }
    }

    // 无户籍信息提示
  .no-household-info {
    margin: 20px 0;
  }

  // 人员信息显示样式
  .person-info-display {
    margin-top: 8px;
    
    .el-tag {
      font-size: 12px;
      padding: 4px 8px;
      border-radius: 4px;
      
      .el-icon {
        margin-right: 4px;
      }
    }
  }

  // 身份证号输入框样式
  .el-input {
    &.is-loading {
      .el-input__wrapper {
        .el-input__suffix {
          .el-icon.is-loading {
            animation: rotating 2s linear infinite;
          }
        }
      }
    }
  }

  @keyframes rotating {
    0% {
      transform: rotate(0deg);
    }
    100% {
      transform: rotate(360deg);
    }
  }
}

  // 响应式设计
  @media (max-width: 768px) {
    .el-form {
      max-width: 100%;
    }
    
    .household-selection {
      .different-household-selection {
        .household-radio-group {
          .household-options {
            gap: 12px;
          }
          
          .household-radio {
            .household-option-card {
              :deep(.el-card__body) {
                padding: 16px;
              }
            }
          }
        }
      }
    }
  }

  // 表单项样式优化
  .el-form-item {
    margin-bottom: 20px;
  }

  .el-input, .el-select, .el-date-picker {
    .el-input__wrapper {
      border-radius: 6px;
    }
  }

  .el-button {
    border-radius: 6px;
    padding: 12px 24px;
    font-weight: 500;
  }

  .el-alert {
    border-radius: 8px;
    
    :deep(.el-alert__content) {
      .el-alert__title {
        font-weight: 600;
      }
    }
  }
}
</style>